console.log("douyin.js loaded");
var kdcConfig = {
    apiUrl: "",
    sayWelcome:false,
    sayGift:false,
    openaiSayWelcome:false,
}
var sayConfig = {
    sayWelcome: '欢迎{{userName}}来到直播间，您可以向chatGPT提一个问题',
    sayGift: '谢谢{{userName}}送的礼物，您可以向chatGPT提一个问题',
}

var newMessage = null;
var kdcObserver = null;


chrome.runtime.sendMessage({type: "register", windowId: "douyin"});
//同步消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse)=> {
    console.log("douyin.js onMessage",request);
    if (request.type == "setApiUrl") {
        kdcConfig.apiUrl = request.data;
        console.log("douyin.js onMessage setConfigApiUrl",kdcConfig);
        sendResponse({code: 200, msg: "收到消息设置API地址成功"});
    }else if (request.type == "setSayWelcome"){
        if(request.data==1){
            startSayWelcome();
        }else{
            stopSayWelcome();
        }
        sendResponse({code: 200, msg: "已"+(request.data==1?"开启":"关闭")+"欢迎播报"});
    }else if (request.type == "setSayGift"){
        if (request.data==1){
            startGiftFun();
        }else{
            stopGiftFun();
        }
        sendResponse({code: 200, msg: "已"+(request.data==1?"开启":"关闭")+"礼物播报"});
    }else if(request.type=="setSendConfig"){
        sayConfig=JSON.parse(request.data);
        sendResponse({code: 200, msg: "已设置播报配置"});
    }
})


//https://chat.openai.com/chat
function startGiftFun() {
    kdcConfig.sayGift=true;

    const targetNode = document.querySelector(".webcast-chatroom___items").firstChild;
    // 观察器的配置（需要观察什么变动）
    const config = { attributes: false, childList: true, subtree: false };
    // 当观察到变动时执行的回调函数
    const callback = function (mutationsList, observer) {
        for (let mutation of mutationsList) {
            if (mutation.addedNodes.length > 0) {
                newMessage=mutation.addedNodes[0].children[0];
                if (newMessage){
                    if(newMessage.getElementsByClassName("Q7mln_nz").length>0){//礼物
                        //newMessage.getElementsByClassName("fTLFnWPf")//礼物图片
                        let userName=newMessage.children[1].textContent;
                        console.log(sayConfig.sayGift.replace("{{userName}}",userName))
                        sayMessage(sayConfig.sayGift.replace("{{userName}}",userName),true);
                    }else{
                        if (newMessage.children[2]){
                            let msg=newMessage.children[2].textContent
                            if(msg.indexOf("请问")>-1){
                                msg=msg.replace("请问","")
                                console.log("openai询问",msg)
                                chrome.runtime.sendMessage({windowId:"openai",type: "toBackgroundToWindowById", data: msg})
                            }
                        }
                    }
                }
            }
        }
    };
    // 创建一个观察器实例并传入回调函数
    kdcObserver = new MutationObserver(callback);
    // 以上述配置开始观察目标节点
    kdcObserver.observe(targetNode, config);
    console.log(kdcObserver)


    // timer= setInterval( ()=> {
    //     const targetNode = document.querySelector(".webcast-chatroom___items").firstChild.querySelectorAll(".webcast-chatroom___item");
    //     if (msgIndex<targetNode.length) {
    //         newMessage = targetNode[msgIndex].children[0];
    //         msgIndex++;
    //         if (newMessage.getElementsByClassName("Q7mln_nz").length > 0) {//礼物
    //             //newMessage.getElementsByClassName("fTLFnWPf")//礼物图片
    //             let userName = newMessage.children[1].textContent;
    //             console.log("感谢" + userName + "送的礼物您可以向chatGPT提一个问题")
    //             sayMessage("感谢" + userName + "送的礼物您可以向chatGPT提一个问题", true);
    //         } else {
    //             let msg=newMessage.children[2].textContent
    //             if(msg.indexOf("请问")>-1){
    //                 msg=msg.replace("请问","")
    //                 console.log("openai询问",msg)
    //                 chrome.runtime.sendMessage({type: "toBackgroundToOpenai", data: msg})
    //             }
    //         }
    //     }
    // },500)
}
function stopGiftFun() {
    kdcConfig.sayGift=false;
    if (kdcObserver){
        kdcObserver.disconnect();
    }
}

function startSayWelcome() {
    kdcConfig.sayWelcome=true;
    $(".webcast-chatroom___bottom-message").bind("DOMNodeInserted", function(data){
        let messageItem=$(data.target).children().children()
        try{
            let userName=$(messageItem[1])[0].textContent

            sayMessage(sayConfig.sayWelcome.replace("{{userName}}",userName));
        }catch (e) {}
    })
}
function stopSayWelcome() {
    kdcConfig.sayWelcome=false;
    $(".webcast-chatroom___bottom-message").unbind("DOMNodeInserted");
}

function sayMessage(currentMessage = "",isGift=false) {
    /*把数据存储在服务端*/
    if(kdcConfig.apiUrl){
        window.fetch(`${kdcConfig.apiUrl}?data=${currentMessage}`)
            .catch((error) => {
                console.log("window.fetch error", error);
            });
    }
    if(kdcConfig.sayWelcome||isGift){
        let say = new window.SpeechSynthesisUtterance(currentMessage || "");
        say.volume = 0.6;
        say.rate=1;
        say.voice = window.speechSynthesis
            .getVoices()
            .filter(
                (voice) => voice.name === "Microsoft Kangkang - Chinese (Simplified, PRC)"
            )[0];
        window.speechSynthesis.speak(say);
    }
}




//background.js添加一个消息监听，并将收到的消息回馈给popup.js



//异步消息监听
// chrome.extension.onMessage.addListener(function (request,sender,callback){
//     console.log("background.js extension onMessage");
//     callback(request);
// });


// var mesgs=["11","22","33","44","55","66","77"];
// var timeouttime=10000;
// var msgindex=0;
// var kdctimeout=null;
// kdctimeout=setInterval(function(){
//     try {
//         chat_textarea.value=mesgs[msgindex];
//         document.getElementById("send_chat_btn").click();
//     }catch (e) {
//     }
//     msgindex++;
//     if(mesgs[msgindex]==null){
//         clearInterval(kdctimeout);
//     }
// },timeouttime)
